#include <iostream>
using std::cout;
using std::endl;



class Singleton
{
public:
    static Singleton * getInstance()
    {
        if(_pInstance == nullptr){
            _pInstance = new Singleton();
        }
        return _pInstance;
    }

    int getData() const {   return _data;   }

private:
    Singleton() {   cout << "Singleton()" << endl;  }
    ~Singleton() {  cout << "~Singleton()" << endl;}

    friend class AutoRelease;
private:
    int _data = 0;
    static Singleton * _pInstance;
};

Singleton * Singleton::_pInstance = nullptr;

class AutoRelease
{
public:
    AutoRelease(Singleton * p)
    : _p(p)
    {   cout << "AutoRelease()" << endl; 
        cout << _p->_data << endl;
    }

    ~AutoRelease() {
        if(_p) {
            delete _p;
            _p = nullptr;
        }
        cout << "~AutoRelease()" << endl;
    }

private:
    Singleton * _p;
};

void test0()
{
    AutoRelease ar(Singleton::getInstance());
    Singleton * p1 = Singleton::getInstance();
    Singleton * p2 = Singleton::getInstance();
    cout << "p1:" << p1 << endl;
    cout << "p2:" << p2 << endl;
    cout << p1->getData() << endl;
    cout << p2->getData() << endl;

}


int main()
{
    test0();
    return 0;
}

